package com.bafa.services;

import java.sql.Date;
import java.sql.ResultSet;
import java.util.Calendar;
import java.util.HashMap;

import com.bafa.dbcache.LeagueCache;
import com.bafa.dbcache.GrabDivision;
import com.bafa.jdbc.DBAccess;
import com.bafa.jdbc.QueryObject;
import com.bafa.jdbc.UpdateObject;
import com.bafa.objects.Match;
import com.bafa.objects.Message;
import com.bafa.objects.season.Round;
import com.bafa.objects.season.RoundMatch;
import com.bafa.objects.season.Season;
import com.bafa.objects.team.Team;
import com.bafa.tables.Keys;

public class FixtureServices {

	/**
	 * 
	 * @param teamA
	 * @param teamB
	 * @param day
	 * @param month
	 * @param year
	 * @param hour
	 * @param minute
	 * @param seasonId
	 * @param division
	 * @return
	 */
	public static Message addFixture(int teamA, int teamB, int day, int month, int year,int hour, int minute, int seasonId, int division){
		Message message = new Message();
		Calendar cal = Calendar.getInstance();
		cal.set(year,month,day);
		long time = cal.getTimeInMillis();
		Date date = new Date(time);
		Match match = new Match();
		match.setID(LeagueCache.getLatestMatchId()+1);
		match.setTeamA(teamA);
		match.setTeamB(teamB);
		match.setDivision(division);
		match.setSeasonId(seasonId);
		match.setDate(date);
		String minutes = "";
		if(minute<10)
			minutes = "0"+minute;
		else
			minutes = ""+minute;
		String timeString = hour+":"+minutes;
		match.setTime(timeString);
		Team teamObjA = RetrieveServices.getTeam(""+teamA);
		Team teamObjB = RetrieveServices.getTeam(""+teamB);
		teamObjA.getStats().enterMatch(match,seasonId);
		teamObjB.getStats().enterMatch(match,seasonId);
		RetrieveServices.getSeason(seasonId+"").enterMatch(match);
		
		DBAccess db = new DBAccess();
		try{
			LeagueCache.storeMatch(match);
			LeagueCache.getUnplayedMatches().put(match.getID(),match.getID());
			db.storeMatch(match);
			db.updateTeam(teamObjA);
			db.updateTeam(teamObjB);
			db.updateSeason(RetrieveServices.getSeason(seasonId+""));
			LeagueCache.setLatestMatchId(match.getID());
			message.addMessage("Fixture added successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
			
		}
		return message;
	}

	
	private static Round createRound(String name,int seasonId, boolean cup){
		Round round = new Round();
		
		round.setCup(cup);
		round.setName(name);
		round.setSeasonId(seasonId);
		
		return round;
	}
	public static void rescheduleAFixture(int matchId, int day, int month, int year,int hour, int minute){
		DBAccess db = new DBAccess();
		
		Match match = RetrieveServices.getMatch(matchId);
		Calendar cal = Calendar.getInstance();
		cal.set(year,month,day);
		String minutes = "";
		if(minute<10)
			minutes = "0"+minute;
		else
			minutes = ""+minute;
		String timeString = hour+":"+minutes;
		long time = cal.getTimeInMillis();
		Date date = new Date(time);
		match.setDate(date);
		match.setTime(timeString);
		try{
			db.updateMatch(match);
			
		
		
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
	}

	public static Message deleteFixture(int matchId){
		DBAccess db = new DBAccess();
		Message message = new Message();
		Match match = RetrieveServices.getMatch(matchId);
		
		RetrieveServices.getTeam(match.getTeamA()+"").getStats().removeFixture(match);
		RetrieveServices.getTeam(match.getTeamB()+"").getStats().removeFixture(match);
		RetrieveServices.getSeason(match.getSeasonId()+"").removeMatch(match);
		LeagueCache.getMatches().remove(match.getID());
		LeagueCache.getUnplayedMatches().remove(match.getID());
		try{
			db.deleteMatch(match);
			message.addMessage("Match has been deleted successfully");
			
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
		}
		return message;
	}

	public static Message addByeFixtureToRound(int roundId, int seasonId, int a, int posA){
		Message message = new Message();
		QueryObject query = new QueryObject(Keys.MATCHES);
		
		DBAccess db = new DBAccess();
		UpdateObject update = new UpdateObject();
		update.addField(Keys.MATCHES_SEASONID,seasonId);
		update.addField(Keys.MATCHES_TEAMB,0);
		update.addField("played",1);
		update.addField("addedA",1);
		update.addField("addedB",1);
		int matchId = 0;
		try{
			ResultSet rs = db.insert(query,update);
			
			while(rs.next()){
				 matchId  = rs.getInt("ID");
			}
			QueryObject queryRound = new QueryObject("roundsformat");
			UpdateObject updateRound = new UpdateObject();
			updateRound.addField("RoundId",roundId);
			updateRound.addField("MatchId",matchId);
			updateRound.addField("A",a);
			updateRound.addField("PosA",posA);
			updateRound.addField("Confirmed",1);
			updateRound.addField("Bye",1);
			db.insert(queryRound,updateRound);
			message.addMessage("Fixture Successfully Added");
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
			//LeagueCache.refreshLatestTeamSeasonMatch(a,matchId,true);
			
		}
		
		return message;
	}
	public static Message addFixtureToRound(int roundId, int day, int month, int year,int hour, int minute, int seasonId, int posA,int posB,int a, int b){
		Message message = new Message();
		QueryObject query = new QueryObject(Keys.MATCHES);
		boolean bye = false;
		if(posA==0||posB==0){
			bye=true;
		}
		DBAccess db = new DBAccess();
		Calendar cal = Calendar.getInstance();
		cal.set(year,month-1,day);
		String minutes = "";
		if(minute<10)
			minutes = "0"+minute;
		else
			minutes = ""+minute;
		String timeString = hour+":"+minutes;
		long time = cal.getTimeInMillis();
		Date date = new Date(time);
		UpdateObject update = new UpdateObject();
		update.addField(Keys.MATCHES_DATE,date);
		update.addField(Keys.MATCHES_SEASONID,seasonId);
		update.addField("Time",timeString);
		if(bye)update.addField("played",1);
		int matchId = 0;
		try{
			ResultSet rs = db.insert(query,update);
			
			while(rs.next()){
				 matchId  = rs.getInt("ID");
			}
			QueryObject queryRound = new QueryObject("roundsformat");
			UpdateObject updateRound = new UpdateObject();
			updateRound.addField("RoundId",roundId);
			updateRound.addField("MatchId",matchId);
			updateRound.addField("A",a);
			updateRound.addField("B",b);
			updateRound.addField("PosA",posA);
			updateRound.addField("PosB",posB);
			
			 db.insert(queryRound,updateRound);
			message.addMessage("Fixture Successfully Added");
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		    //LeagueCache.refreshSeason(seasonId);
			db.disconnect();
			
		}
		return message;
	}
	
	/**
	 * 
	 * @param teamA
	 * @param teamB
	 * @param day
	 * @param month
	 * @param year
	 * @param hour
	 * @param minute
	 * @param seasonId
	 * @param division
	 * @return
	 */
	public static Message addRound(String teamA, String teamB, int day, int month, int year,int hour, int minute, int seasonId,boolean knockout,String roundName,boolean cup, int roundId){
		Message message = new Message();
		Calendar cal = Calendar.getInstance();
		cal.set(year,month-1,day);
		long time = cal.getTimeInMillis();
		Date date = new Date(time);
		Match match = new Match();
		match.setID(LeagueCache.getLatestMatchId()+1);
		match.setSeasonId(seasonId);
		match.setDate(date);
		String minutes = "";
		if(minute<10)
			minutes = "0"+minute;
		else
			minutes = ""+minute;
		String timeString = hour+":"+minutes;
		match.setTime(timeString);
		if(knockout){
			Round round = null;
			if(RetrieveServices.getSeason(seasonId+"").getCupRounds().containsKey(roundName)){
				round = (Round)RetrieveServices.getSeason(seasonId+"").getCupRounds().get(roundName);
			}else{
				round = createRound(roundName,seasonId,cup);
			}
			RoundMatch roundMatch = new RoundMatch();
			roundMatch.setMatchId(match.getID());
			if(teamA.indexOf("-")>0){
				
				int previousGroup = new Integer(teamA.substring(0,1)).intValue();
				int previousPosition = new Integer(teamA.substring(2)).intValue();
				roundMatch.setPreviousGroupA(true);
				roundMatch.setPreviousIdA(previousGroup);
				roundMatch.setPreviousPositionA(previousPosition);
			}else{
				roundMatch.setPreviousGroupA(false);
				roundMatch.setPreviousIdA(new Integer(teamA).intValue());
			}
			if(teamB.indexOf("-")>0){
				int previousGroup = new Integer(teamB.substring(0,1)).intValue();
				int previousPosition = new Integer(teamB.substring(2)).intValue();
				roundMatch.setPreviousGroupB(true);
				roundMatch.setPreviousIdB(previousGroup);
				roundMatch.setPreviousPositionB(previousPosition);
			}else{
				roundMatch.setPreviousGroupB(false);
				roundMatch.setPreviousIdB(new Integer(teamB).intValue());
			}
			
			
			round.addMatches(roundId,roundMatch);
			RetrieveServices.getSeason(seasonId+"").addCupRounds(roundName,round);
		}
		DBAccess db = new DBAccess();
		try{
			LeagueCache.storeMatch(match);
			LeagueCache.getUnplayedMatches().put(match.getID(),match.getID());
			db.storeMatch(match);
			
			db.updateSeason(RetrieveServices.getSeason(seasonId+""));
			LeagueCache.setLatestMatchId(match.getID());
			message.addMessage("Fixture added successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
			
		}
		return message;
	}

	public static Message addRound(RoundMatch roundMatch,  int day, int month, int year,int hour, int minute, int seasonId,boolean knockout,String roundName,boolean cup, int roundId){
		Message message = new Message();
		Calendar cal = Calendar.getInstance();
		cal.set(year,month-1,day);
		long time = cal.getTimeInMillis();
		Date date = new Date(time);
		Match match = new Match();
		match.setID(LeagueCache.getLatestMatchId()+1);
		match.setSeasonId(seasonId);
		match.setDate(date);
		String minutes = "";
		if(minute<10)
			minutes = "0"+minute;
		else
			minutes = ""+minute;
		String timeString = hour+":"+minutes;
		match.setTime(timeString);
		if(knockout){
			Round round = null;
			if(RetrieveServices.getSeason(seasonId+"").getCupRounds().containsKey(roundName)){
				round = (Round)RetrieveServices.getSeason(seasonId+"").getCupRounds().get(roundName);
			}else{
				round = createRound(roundName,seasonId,cup);
			}	
			round.addMatches(roundId,roundMatch);
			RetrieveServices.getSeason(seasonId+"").addCupRounds(roundName,round);
		}
		DBAccess db = new DBAccess();
		try{
			LeagueCache.storeMatch(match);
			LeagueCache.getUnplayedMatches().put(match.getID(),match.getID());
			db.storeMatch(match);
			
			db.updateSeason(RetrieveServices.getSeason(seasonId+""));
			LeagueCache.setLatestMatchId(match.getID());
			message.addMessage("Fixture added successfully.");
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			db.disconnect();
			
		}
		return message;
	}

	
	
}
